import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { ACCESS_TOKEN, INDEX_MAIN_PAGE_PATH, CURRENT_PREFIX, INTERFACE_PREFIX,OAUTH2_LOGIN_PAGE_PATH_EASY_WORK } from '@/store/mutation-types'
import { generateIndexRouter } from "@/utils/util"
import { login } from "@/utils/login";
import { Tip } from "@/utils";
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/user/login', '/user/register', '/user/register-result', '/user/alteration'] // no redirect whitelist
whiteList.push(OAUTH2_LOGIN_PAGE_PATH_EASY_WORK);
var jsApiAuthReady = false;
router.beforeEach((to, from, next) => {
  /* 根据路由meta配置的appId设置接口前缀缓存 appId是每个模块的第一级路由的id */
  let appId = to.meta.appId
  let Allprefix = Vue.ls.get(INTERFACE_PREFIX)
  if (appId && Allprefix) {
    Vue.ls.set(CURRENT_PREFIX, Allprefix[appId], 7 * 24 * 60 * 60 * 1000)
    store.commit('SET_CURRENT_PREFIX',Allprefix[appId])
  } else {
    Vue.ls.set(CURRENT_PREFIX, '', 7 * 24 * 60 * 60 * 1000)
    store.commit('SET_CURRENT_PREFIX','')
  }
  /* 根据路由meta配置的appId设置接口前缀缓存 appId是每个模块的第一级路由的id */
  NProgress.start() // start progress bar
  if (Vue.ls.get(ACCESS_TOKEN)) {
    hasAccessTokenAction(to, from, next)
  } else {
    login()
      .then((data) => {
        console.log("then当前的环境是：", localStorage.getItem("currentEnvironment"));
        if (store.getters.permissionList.length === 0) {
          notPermission(to, from, next)
        } else {
          next()
        }
      })
      .catch((e) => {
        console.log("catch当前的环境是：", localStorage.getItem("currentEnvironment"));
        console.log('走的rejectTye类型是：', e.rejectType);
        if (e && e.rejectType == 'browser') {
          store.dispatch('Logout').then(() => {
            Vue.ls.remove(ACCESS_TOKEN)
            noAccessTokenAction(to, from, next);
          })

        }
      })
  }
})
function noAccessTokenAction(to, from, next) {
  if (whiteList.indexOf(to.path) !== -1) {
    // 在免登录白名单，直接进入
    next()
  } else {
    next({ path: '/user/login', query: { redirect: to.fullPath } })
    NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it

  }
}

function hasAccessTokenAction(to, from, next) {
  /* has token */
  if (to.path === '/user/login') {
    next({ path: INDEX_MAIN_PAGE_PATH })
    NProgress.done()
  } else {
    if (store.getters.permissionList.length === 0) {
      notPermission(to, from, next)
    } else {
      next()
    }
  }
}
function notPermission(to, from, next) {
  store.dispatch('GetPermissionList').then(res => {
    const menuData = res.result.menu;
    if (menuData === null || menuData === "" || menuData === undefined) {
      return;
    }
    let constRoutes = [];
    constRoutes = generateIndexRouter(menuData);
    store.dispatch('UpdateAppRouter', { constRoutes }).then(() => {
      router.addRoutes(store.getters.addRouters)
      const redirect = decodeURIComponent(from.query.redirect || to.path)
      if (to.path === redirect) {
        next({ ...to, replace: true })
      } else {
        next({ path: redirect })
      }
    })
  })
    .catch((err) => {
      Tip.error(err);
      NProgress.done()
      store.dispatch('Logout').then(() => {
        next({ path: '/user/login' })
        // next({ path: '/user/login', query: { redirect: to.fullPath } })
      })
    })
}
router.afterEach(() => {
  NProgress.done() // finish progress bar
})
